﻿using LOG;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Timers;

namespace CWCS.Core.Library.SocketManager
{
    public class CRLSocketServer
    {
        private SocketServer ss;
        public delegate void NotifyCommandHander_SS(string Command, object msg);
        public event NotifyCommandHander_SS Notify;
        private Timer CheckTimer = null;

        private Log log;
        private string _ip = "", _port = "";
        public Timer CheckConnectTimer
        {
            get
            {
                if (CheckTimer == null)
                {
                    CheckTimer = new Timer();
                }
                return CheckTimer;
            }
        }
        public void ServerStart(string ip, int port)
        {
            _ip = ip;
            _port = port.ToString();
            log = new Log(port + "json日志", ".\\OCV与DCIR\\OCV与DCIR日志\\");
            ss = new SocketServer(ip, port);
            ss.NotifyEventHanlder += new DNotifyMessage(ss_NotifyEventHanlder);
            ss.StartListening();
            //CheckConnectTimer.Start();
        }
        private void ss_NotifyEventHanlder(string Command, object Mesg)
        {
            try
            {
                string msg = Mesg.ToString().TrimEnd(' ').TrimEnd('\0');
                string cmd = Command;
                if (Command == "RecvData" && msg.Length > 3)
                {
                    log.WriteLog(System.DateTime.Now.ToString("yyyyMMdd") + "接受Json" + _port, msg);
                }
                if (Command != "SendData")
                {
                    if (Command == "Connect")
                        cmd = "Heart";
                    ENotify(cmd, msg);
                }
            }
            catch (Exception e)
            {
                log.WriteLog(System.DateTime.Now.ToString("yyyyMMdd") + "接收异常" + _ip, e.Message + e.Source + e.StackTrace + e.TargetSite);
            }
        }
        public void SendMessage(byte[] byt)
        {
            ss.SendMessage(byt);
        }
        private void ENotify(string Command, object Mesg)
        {
            if (Notify != null)
                Notify(Command, Mesg);
        }
    }
}
